import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect, getLocale, history, Link, Prompt } from 'umi';
import type { GlobalModelState } from '@/models/global';
import type { MenuState } from '@/models/menu';
import type { BasicLayoutProps } from '@ant-design/pro-layout';
import type { Dispatch } from 'umi';
import { BasicLayout as ProLayoutComponents, GridContent, RouteContext } from '@ant-design/pro-layout';
import { Icon, SmartGrid } from 'gantd';
import { Badge } from 'antd';
import classnames from 'classnames';
import { get } from 'lodash';
import { AliveScope } from 'react-activation';
import styles from './index.less';

let initFlag = false;

const BasicLayout = (props) => {
  const { dispatch, route, location, globalLoading, serveMenu, collapsed, settings, children } = props;
  const { BASE_CONFIG, showBreadcrumb, fullscreen, MAIN_CONFIG } = settings;
  const { logoImageWhite, logoImage, logoName } = BASE_CONFIG;
  const {
    slideWidth,
    navTheme,
    slideCollapsedWidth,
    showNavigationButton,
    waterFontSize,
    lightWaterFontColor,
    darkWaterFontColor,
    waterFontRotate,
    waterFontAlpha,
    waterPadding,
    waterStatus,
    waterShowTime,
    waterText,
    themeType,
    autoDetectVersion,
  } = MAIN_CONFIG;

  const [menuProps, setMenuProps] = useState<any>({});

  //获取菜单名字展示
  const getMenuName = useCallback((item: any) => {
    //样式
    const clsName = classnames('custom-menu-item-link', 'dark');
    //超链接
    const target = item.isUrl ? '_blank' : undefined;

    let menuItem = (
      <Link className={clsName} to={item.path ? item.path : '/'} title={item.name} target={target}>
        <Icon type={item.icon ? item.icon : 'unordered-list'} />
        {item.name}
      </Link>
    );

    //没有 path 或者非子节点
    if (!item.path || item.leaf !== true) {
      menuItem = (
        <div className={clsName} title={item.name}>
          <Icon type={item.icon ? item.icon : 'unordered-list'} />
          {item.name}
        </div>
      );
    } else if (item.path === '/all') {
      // 全部菜单
      menuItem = (
        <span className={clsName} style={{ cursor: 'pointer' }} onClick={() => {}}>
          <span style={{ cursor: 'pointer' }} onMouseEnter={() => {}} onMouseLeave={() => {}}>
            <Icon type={item.icon ? item.icon : 'unordered-list'} />
            {item.name}
          </span>
        </span>
      );
    } else if (item.openTabPath && item.openTabPath.startsWith('http')) {
      menuItem = (
        <div className={clsName} title={item.name} onClick={() => {}}>
          <Icon type={item.icon ? item.icon : 'unordered-list'} />
          {item.name}
        </div>
      );
    }

    return (
      <div className="custom-menu-item" title={item.name}>
        {menuItem}
        {item.badge && (
          <div className="custom-menu-item-count">
            <Badge count={item.badge} />
          </div>
        )}
      </div>
    );
  }, []);

  //获取菜单数据
  const getMenuDataName = useCallback(
    (list = []) => {
      return list.map((item: any) => {
        if (get(item, 'children.length')) {
          const name = getMenuName(item);
          return {
            ...item,
            icon: undefined, // 去掉icon使菜单只显示name
            name,
            children: getMenuDataName(get(item, 'children')),
          };
        }
        return item;
      });
    },
    [getMenuName],
  );

  const convertMenuData = useMemo(() => getMenuDataName(serveMenu), [serveMenu, getMenuDataName]);

  const menuDataRender = useCallback(() => {
    const menu = [
      {
        id: 'all',
        key: 'all',
        icon: 'appstore',
        iconType: 'ant',
        name: '全部菜单',
        path: '/all',
        hideInMenu: false,
      },
    ];
    return menu.concat(...convertMenuData);
  }, [convertMenuData]);

  //更新主布局
  const syncLayout = (collapsed: boolean) => {
    let finished = false;
    const time = setInterval(() => {
      const sizeElement = document.getElementsByClassName('ant-pro-sider-menu-sider')[0];
      if (finished) {
        clearInterval(time);
      } else {
        if (sizeElement) {
          const width = sizeElement.offsetWidth;
          const targetwidth = collapsed ? 30 : 180;
          if (width == targetwidth) {
            window.dispatchEvent(new Event('resize'));
            finished = true;
          }
        }
      }
    }, 50);
    setTimeout(() => {
      if (time) {
        clearInterval(time);
        window.dispatchEvent(new Event('resize'));
      }
    }, 500);
  };

  //更新主菜单收缩
  const updateMenuCollapse = (_collapsed: boolean) => {
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: _collapsed,
    });
    syncLayout(_collapsed);
  };

  //主菜单收缩
  const toggleMenuCollapse = (_collapsed: boolean) => {
    if (initFlag == false) {
      initFlag = true;
      if (_collapsed) {
        updateMenuCollapse(_collapsed);
      }
      return;
    }
    updateMenuCollapse(_collapsed);
  };

  //页面满屏
  const finFullScreen = () => {
    const urlFull = window.location.search.indexOf('full=true') >= 0;
    if (urlFull) return true;
    return fullscreen;
  };

  useEffect(() => {
    setMenuProps({
      onOpenChange: (keys) => {
        setMenuProps((pre) => ({
          ...pre,
          openKeys: keys,
        }));
      },
    });
  }, []);

  useEffect(() => {
    if (dispatch) {
      // 获取本地配置信息
      dispatch({ type: 'settings/setGlobalTheme' });
      // 获取当前用户集成信息，用户代理委托  用户授权功能点	是否为超级管理员	用户所属角色	用户授权主菜单	用户信息
      dispatch({ type: 'user/fetchCurrent', payload: { route } });
      dispatch({ type: 'organization/fetchAllOrg' }); // 获取全局组织、角色、用户数据
      dispatch({ type: 'organization/fetchAllUserGroup' }); // 获取全局组织、角色、用户数据
    }
  }, []);

  return (
    <AliveScope>
      <div className={classnames('gant-layout', finFullScreen() ? styles.fullscreen : '')}>
        <ProLayoutComponents
          title={BASE_CONFIG.logoName}
          logo={navTheme === 'dark' ? logoImageWhite : logoImage}
          disableMobile
          onCollapse={() => toggleMenuCollapse(!collapsed)}
          menuItemRender={getMenuName}
          breadcrumbRender={(routers = []) => routers}
          siderWidth={slideWidth}
          rightContentRender={() => <></>}
          footerRender={false} // 去掉版权信息
          menuDataRender={menuDataRender}
          menuHeaderRender={(logo, title) => (
            <div
              onClick={() => {}}
              className={styles.logo}
              style={{
                paddingLeft: collapsed ? '0px' : '5px',
                justifyContent: collapsed ? 'center' : 'left',
              }}
            >
              <div
                className={styles.img}
                style={{
                  backgroundImage: `url(${navTheme === 'dark' ? logoImageWhite : logoImage})`,
                }}
              />
              <div style={{ display: collapsed ? 'none' : 'inline-block' }}>{title}</div>
            </div>
          )}
          collapsed={collapsed}
          menuProps={menuProps}
          pageTitleRender={() => 'UMIAPP'}
          theme="dark"
          {...MAIN_CONFIG}
        >
          <GridContent>
            <RouteContext.Consumer>
              {({ breadcrumb }) => {
                return (
                  <>
                    <div style={{ position: 'relative' }}>
                      <div className={styles.waterMask} />
                      {children}
                    </div>
                  </>
                );
              }}
            </RouteContext.Consumer>
          </GridContent>
        </ProLayoutComponents>
      </div>
    </AliveScope>
  );
};

export default connect(({ global, menu, settings }: { global: GlobalModelState; menu: MenuState }) => ({
  serveMenu: menu.serveMenu,
  globalLoading: global.globalLoading,
  collapsed: global.collapsed,
  settings,
}))(BasicLayout as any);
